<!DOCTYPE html >
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <title>设置菜单</title>
    <script th:replace="common/head::static"></script>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div id="layuiTreeSysMenu"></div>
        </div>
    </div>
    <div class="layui-btn-container">
        <button type="button" class="layui-btn" lay-setSysMenu="getChecked">保存</button>
        <button type="button" class="layui-btn layui-btn-primary" lay-setSysMenu="reload">重置</button>
    </div>
</div>

<script th:src="@{/common/js/common.js}"></script>
<script th:inline="javascript">

    const sysRoleId = [[${sysRoleId}]];

    const checkedIds = [[${checkedIds}]];

    layui.use(['tree', 'util'], function () {
        const $ = layui.jquery
            , util = layui.util
            , layer = layui.layer
            , tree = layui.tree;

        Common.ajaxGetNoParams(ctx + '/sysMenu/findAll', function (res) {
            if (res.value === 200) {
                tree.render({
                    elem: '#layuiTreeSysMenu'
                    , data: res.data
                    , id: 'layuiTreeSysMenu'
                    , accordion: true
                    , showCheckbox: true
                });
                tree.setChecked('layuiTreeSysMenu', checkedIds);
            }
        });

        //按钮事件
        util.event('lay-setSysMenu', {
            getChecked: function (othis) {
                const checkedData = tree.getChecked('layuiTreeSysMenu'); //获取选中节点的数据
                const sysMenuIds = [];
                $.each(checkedData, function (index, data) {
                    sysMenuIds.push(data.id);
                    $.each(data.children, function (index, child) {
                        sysMenuIds.push(child.id);
                    });
                });
                if (sysMenuIds.length === 0) {
                    layer.msg('未勾选任何菜单', function () {
                        return false;
                    });
                } else {
                    const params = {
                        sysMenuIds: sysMenuIds.join(","),
                        sysRoleId: sysRoleId
                    }
                    Common.ajaxPut(ctx + '/sysRole/setSysMenu', params, function (res) {
                        if (res.value === 200) {
                            layer.msg(res.message, {icon: 1, time: 1000}, function () {
                                Common.closeFrame();
                            });
                        } else {
                            layer.msg(res.message, {icon: 2, time: 2000});
                        }
                    });
                }
            }
            , reload: function () {
                //重载实例
                tree.reload('layuiTreeSysMenu', {});
            }
        });

    });

</script>
</body>
</html>